import TestPlayerView from "./TestPlayerView"

const {ccclass, property} = cc._decorator;

@ccclass
export default class TestMapView extends cc.Component {

    @property(TestPlayerView)
    player: TestPlayerView = null;

    @property(cc.Camera)
    camera: cc.Camera = null;

    obsLayer: cc.TiledLayer = null;

    onLoad () {
        //this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd.bind(this));
        let tp: cc.TiledMap = this.getComponent(cc.TiledMap);
        this.obsLayer = tp.getLayer("obstacle");
        this.initMapLayer();
    }

    start () {

    }

    public initMapLayer():void{

        let tiledSize = this.obsLayer.getMapTileSize();
        let layerSize = this.obsLayer.getLayerSize();
 
        for(let i = 0;i < layerSize.width;i++){
            for (let j = 0; j < layerSize.height; j++) {
                let tiled = this.obsLayer.getTiledTileAt(i,j,true);
                if (tiled.gid != 0) {
                    tiled.node.group = "default";
                    let body = tiled.node.addComponent(cc.RigidBody);
                    body.type = cc.RigidBodyType.Static;
                    body.awakeOnLoad = true;
                    let collider = tiled.node.addComponent(cc.PhysicsBoxCollider);
                    collider.offset = cc.v2(tiledSize.width/2,tiledSize.height/2);
                    collider.size = tiledSize;
                    collider.apply();
                }
                 
            }
        }

    }

    public onTouchEnd(event: cc.Event.EventTouch): void {
        let view_pos: cc.Vec2 = event.getLocation();
        //将屏幕坐标系转换成世界坐标系
        let w_pos: cc.Vec2 = new cc.Vec2();
        this.camera.getScreenToWorldPoint(view_pos, w_pos);

        //将世界坐标系转换成节点坐标系
        let pos = this.node.parent.convertToNodeSpaceAR(w_pos);

        this.player.moveToTarget(pos);
    }

    // update (dt) {}
}
